import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.ConnectedStreams;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.CoMapFunction;
import org.apache.flink.streaming.api.functions.co.CoProcessFunction;
import org.apache.flink.util.Collector;

public class CoMapExample {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        DataStream<Integer> stream1 = env.fromElements(1,2,3);
        DataStream<Long> stream2 =  env.fromElements(1L,2L,3L);

        ConnectedStreams<Integer, Long> connectedStreams = stream1.connect(stream2);

        ConnectedStreams<Integer, Long>  keyedStream = connectedStreams.keyBy(new KeySelector<Integer, String>() {
            @Override
            public String getKey(Integer value) throws Exception {
                return String.valueOf(value);
            }
        }, new KeySelector<Long, String>() {
            @Override
            public String getKey(Long value) throws Exception {
                return String.valueOf(value);
            }
        });

        keyedStream.map(new CoMapFunction<Integer, Long, String>() {
            @Override
            public String map1(Integer value) throws Exception {
                return "int" + value ;
            }

            @Override
            public String map2(Long value) throws Exception {
                return "long" + value ;
            }
        });


        keyedStream.process(new CoProcessFunction<Integer, Long, String>() {
            @Override
            public void processElement1(Integer value, CoProcessFunction<Integer, Long, String>.Context ctx, Collector<String> out) throws Exception {
                out.collect(value + "" + ctx.timerService());
            }

            @Override
            public void processElement2(Long value, CoProcessFunction<Integer, Long, String>.Context ctx, Collector<String> out) throws Exception {
                out.collect(value + "");
            }
        }).print("keyed");


        //将一条Integer 流和一条Long 流合并，转换成 String 输出
        SingleOutputStreamOperator<String> result = connectedStreams.map(new CoMapFunction<Integer, Long, String>() {
            @Override
            //.map1()就是对第一条流中数据的 map 操作
            public String map1(Integer value) throws Exception {
                return "int" + value ;
            }

            @Override
            //.map2()则是针对第二条流
            public String map2(Long value) throws Exception {
                return "long" + value ;
            }
        });

        result.print("result");

        env.execute();

    }
}
